<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片改色工具</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <div style="margin-bottom: 20px;">
            <button onclick="window.location.href='index.html'" class="gallery-btn" style="display: flex; align-items: center; gap: 8px;">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M19 12H5M12 19l-7-7 7-7"></path>
                </svg>
                返回首页
            </button>
        </div>
        <h1>图片改色工具</h1>
        
        <div class="upload-section">
            <input type="file" id="image-upload" accept=".svg,.png,.jpg,.jpeg" style="display: none;">
            <button id="upload-btn" class="primary-btn">选择图片</button>
            <div id="file-info" style="margin-top: 10px; color: #666;"></div>
        </div>

        <div class="color-picker-section" style="margin: 20px 0; display: none;" id="color-section">
            <h3>选择颜色</h3>
            <div style="margin-bottom: 15px;">
                <label>
                    <input type="radio" name="color-type" value="solid" checked> 单色
                </label>
                <label style="margin-left: 20px;">
                    <input type="radio" name="color-type" value="gradient"> 渐变色
                </label>
            </div>
            
            <div id="solid-color-section">
                <input type="color" id="color-selector" value="#ff6b6b" style="width: 80px; height: 80px; border-radius: 50%; border: 3px solid #ddd;">
                <div style="margin-top: 10px;">
                    <span id="color-hex">#ff6b6b</span>
                </div>
            </div>
            
            <div id="gradient-color-section" style="display: none; margin-top: 15px;">
                <div style="display: flex; gap: 10px; align-items: center; margin-bottom: 10px;">
                    <label>起始颜色:</label>
                    <input type="color" id="gradient-start" value="#ff6b6b" style="width: 40px; height: 40px; border-radius: 50%;">
                    <label>结束颜色:</label>
                    <input type="color" id="gradient-end" value="#4ecdc4" style="width: 40px; height: 40px; border-radius: 50%;">
                </div>
                <div style="margin-bottom: 10px;">
                    <label>渐变方向:</label>
                    <select id="gradient-direction">
                        <option value="horizontal">水平</option>
                        <option value="vertical">垂直</option>
                        <option value="diagonal">对角线</option>
                        <option value="radial">径向</option>
                    </select>
                </div>
                <div id="gradient-preview" style="width: 100%; height: 40px; border: 1px solid #ddd; border-radius: 4px;"></div>
            </div>
        </div>

        <div class="preview-section" style="margin: 20px 0; display: none;" id="preview-section">
            <h3>预览</h3>
            <div style="display: flex; gap: 40px; justify-content: center;">
                <div>
                    <h4>原图</h4>
                    <img id="original-preview" style="max-width: 200px; max-height: 200px; border: 2px dashed #ddd;">
                </div>
                <div>
                    <h4>改色后</h4>
                    <img id="colored-preview" style="max-width: 200px; max-height: 200px; border: 2px solid #007bff;">
                </div>
            </div>
        </div>

        <div class="action-buttons" style="margin: 30px 0; display: none; justify-content: center;" id="action-section">
            <button id="save-svg-btn" class="primary-btn">
                <div>保存为SVG</div>
            </button>
            <button id="save-png-btn" class="primary-btn">
                <div>保存为PNG</div>
            </button>
        </div>

        <div id="status-bar" class="status-bar"></div>
    </div>

    <script src="script.js"></script>
    <script>
        // 页面特定的JavaScript代码
        document.addEventListener('DOMContentLoaded', function() {
            const uploadBtn = document.getElementById('upload-btn');
            const imageUpload = document.getElementById('image-upload');
            const colorSelector = document.getElementById('color-selector');
            const colorHex = document.getElementById('color-hex');
            const originalPreview = document.getElementById('original-preview');
            const coloredPreview = document.getElementById('colored-preview');
            const saveSvgBtn = document.getElementById('save-svg-btn');
            const savePngBtn = document.getElementById('save-png-btn');
            const statusBar = document.getElementById('status-bar');
            const fileInfo = document.getElementById('file-info');
            const colorSection = document.getElementById('color-section');
            const previewSection = document.getElementById('preview-section');
            const actionSection = document.getElementById('action-section');

            let currentImage = null;
            let currentImageType = '';

            // 上传按钮点击事件
            uploadBtn.addEventListener('click', () => {
                imageUpload.click();
            });

            // 文件选择事件
            imageUpload.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(event) {
                        currentImage = event.target.result;
                        currentImageType = file.type;
                        
                        fileInfo.textContent = `已选择: ${file.name} (${(file.size / 1024).toFixed(1)}KB)`;
                        
                        // 显示颜色选择器和预览
                        colorSection.style.display = 'block';
                        previewSection.style.display = 'block';
                        actionSection.style.display = 'flex';
                        
                        // 显示原图预览
                        originalPreview.src = currentImage;
                        updateColoredPreview();
                    };
                    reader.readAsDataURL(file);
                }
            });

            // 颜色选择器变化事件
            colorSelector.addEventListener('input', (e) => {
                colorHex.textContent = e.target.value;
                updateColoredPreview();
            });

            // 渐变色控件事件
            const colorTypeRadios = document.querySelectorAll('input[name="color-type"]');
            const gradientStart = document.getElementById('gradient-start');
            const gradientEnd = document.getElementById('gradient-end');
            const gradientDirection = document.getElementById('gradient-direction');
            const gradientPreview = document.getElementById('gradient-preview');
            const solidColorSection = document.getElementById('solid-color-section');
            const gradientColorSection = document.getElementById('gradient-color-section');

            // 颜色类型切换
            colorTypeRadios.forEach(radio => {
                radio.addEventListener('change', (e) => {
                    if (e.target.value === 'solid') {
                        solidColorSection.style.display = 'block';
                        gradientColorSection.style.display = 'none';
                    } else {
                        solidColorSection.style.display = 'none';
                        gradientColorSection.style.display = 'block';
                        updateGradientPreview();
                    }
                    updateColoredPreview();
                });
            });

            // 渐变色变化事件
            gradientStart.addEventListener('input', () => {
                updateGradientPreview();
                updateColoredPreview();
            });

            gradientEnd.addEventListener('input', () => {
                updateGradientPreview();
                updateColoredPreview();
            });

            gradientDirection.addEventListener('change', () => {
                updateGradientPreview();
                updateColoredPreview();
            });

            // 更新渐变色预览
            function updateGradientPreview() {
                const startColor = gradientStart.value;
                const endColor = gradientEnd.value;
                const direction = gradientDirection.value;
                
                let gradient = '';
                if (direction === 'horizontal') {
                    gradient = `linear-gradient(to right, ${startColor}, ${endColor})`;
                } else if (direction === 'vertical') {
                    gradient = `linear-gradient(to bottom, ${startColor}, ${endColor})`;
                } else if (direction === 'diagonal') {
                    gradient = `linear-gradient(to bottom right, ${startColor}, ${endColor})`;
                } else if (direction === 'radial') {
                    gradient = `radial-gradient(circle, ${startColor}, ${endColor})`;
                }
                
                gradientPreview.style.background = gradient;
            }

            // 更新改色预览
            function updateColoredPreview() {
                if (currentImage) {
                    const colorType = document.querySelector('input[name="color-type"]:checked').value;
                    
                    if (currentImageType === 'image/svg+xml') {
                        // SVG改色预览
                        if (colorType === 'solid') {
                            processSvgColor(currentImage, colorSelector.value)
                                .then(coloredSvg => {
                                    coloredPreview.src = 'data:image/svg+xml;base64,' + btoa(coloredSvg);
                                });
                        } else {
                            processSvgGradient(currentImage, gradientStart.value, gradientEnd.value, gradientDirection.value)
                                .then(coloredSvg => {
                                    coloredPreview.src = 'data:image/svg+xml;base64,' + btoa(coloredSvg);
                                });
                        }
                    } else {
                        // PNG/JPG改色预览
                        if (colorType === 'solid') {
                            processImageColor(currentImage, colorSelector.value)
                                .then(coloredImage => {
                                    coloredPreview.src = coloredImage;
                                });
                        } else {
                            processImageGradient(currentImage, gradientStart.value, gradientEnd.value, gradientDirection.value)
                                .then(coloredImage => {
                                    coloredPreview.src = coloredImage;
                                });
                        }
                    }
                }
            }

            // 保存按钮事件
            saveSvgBtn.addEventListener('click', () => {
                if (currentImage) {
                    const colorType = document.querySelector('input[name="color-type"]:checked').value;
                    
                    if (currentImageType === 'image/svg+xml') {
                        if (colorType === 'solid') {
                            processSvgColor(currentImage, colorSelector.value)
                                .then(svgContent => {
                                    downloadFile(svgContent, 'colored-image.svg', 'image/svg+xml');
                                    updateStatus('SVG已保存并应用颜色');
                                });
                        } else {
                            processSvgGradient(currentImage, gradientStart.value, gradientEnd.value, gradientDirection.value)
                                .then(svgContent => {
                                    downloadFile(svgContent, 'gradient-image.svg', 'image/svg+xml');
                                    updateStatus('SVG已保存并应用渐变色');
                                });
                        }
                    } else {
                        if (colorType === 'solid') {
                            processImageColor(currentImage, colorSelector.value)
                                .then(dataUrl => {
                                    // 将图片转换为SVG
                                    const img = new Image();
                                    img.onload = function() {
                                        const svgContent = `<svg width="${img.width}" height="${img.height}" xmlns="http://www.w3.org/2000/svg">
                                            <image href="${dataUrl}" width="${img.width}" height="${img.height}"/>
                                        </svg>`;
                                        downloadFile(svgContent, 'colored-image.svg', 'image/svg+xml');
                                        updateStatus('SVG已保存并应用颜色');
                                    };
                                    img.src = dataUrl;
                                });
                        } else {
                            processImageGradient(currentImage, gradientStart.value, gradientEnd.value, gradientDirection.value)
                                .then(dataUrl => {
                                    // 将图片转换为SVG
                                    const img = new Image();
                                    img.onload = function() {
                                        const svgContent = `<svg width="${img.width}" height="${img.height}" xmlns="http://www.w3.org/2000/svg">
                                            <image href="${dataUrl}" width="${img.width}" height="${img.height}"/>
                                        </svg>`;
                                        downloadFile(svgContent, 'gradient-image.svg', 'image/svg+xml');
                                        updateStatus('SVG已保存并应用渐变色');
                                    };
                                    img.src = dataUrl;
                                });
                        }
                    }
                }
            });

            savePngBtn.addEventListener('click', () => {
                if (currentImage) {
                    const colorType = document.querySelector('input[name="color-type"]:checked').value;
                    
                    if (currentImageType === 'image/svg+xml') {
                        if (colorType === 'solid') {
                            processSvgColor(currentImage, colorSelector.value)
                                .then(svgContent => {
                                    convertSvgToPng(svgContent)
                                        .then(pngBlob => {
                                            downloadBlob(pngBlob, 'colored-image.png', 'image/png');
                                            updateStatus('PNG已保存并应用颜色');
                                        });
                                });
                        } else {
                            processSvgGradient(currentImage, gradientStart.value, gradientEnd.value, gradientDirection.value)
                                .then(svgContent => {
                                    convertSvgToPng(svgContent)
                                        .then(pngBlob => {
                                            downloadBlob(pngBlob, 'gradient-image.png', 'image/png');
                                            updateStatus('PNG已保存并应用渐变色');
                                        });
                                });
                        }
                    } else {
                        if (colorType === 'solid') {
                            processImageColor(currentImage, colorSelector.value)
                                .then(dataUrl => {
                                    // 直接下载处理后的图片
                                    fetch(dataUrl)
                                        .then(res => res.blob())
                                        .then(blob => {
                                            downloadBlob(blob, 'colored-image.png', 'image/png');
                                            updateStatus('PNG已保存并应用颜色');
                                        });
                                });
                        } else {
                            processImageGradient(currentImage, gradientStart.value, gradientEnd.value, gradientDirection.value)
                                .then(dataUrl => {
                                    // 直接下载处理后的图片
                                    fetch(dataUrl)
                                        .then(res => res.blob())
                                        .then(blob => {
                                            downloadBlob(blob, 'gradient-image.png', 'image/png');
                                            updateStatus('PNG已保存并应用渐变色');
                                        });
                                });
                        }
                    }
                }
            });

            // 工具函数
            function processSvgColor(svgContent, color) {
                return new Promise((resolve) => {
                    const parser = new DOMParser();
                    const svgDoc = parser.parseFromString(svgContent, 'image/svg+xml');
                    const svgElement = svgDoc.documentElement;
                    
                    // 修改所有路径和形状的颜色
                    const elementsToColor = svgElement.querySelectorAll('path, circle, rect, ellipse, polygon, line, polyline');
                    elementsToColor.forEach(element => {
                        if (element.hasAttribute('fill') && element.getAttribute('fill') !== 'none') {
                            element.setAttribute('fill', color);
                        }
                        if (element.hasAttribute('stroke') && element.getAttribute('stroke') !== 'none') {
                            element.setAttribute('stroke', color);
                        }
                    });
                    
                    const processedSvg = new XMLSerializer().serializeToString(svgDoc);
                    resolve(processedSvg);
                });
            }

            function processSvgGradient(svgContent, startColor, endColor, direction) {
                return new Promise((resolve) => {
                    const parser = new DOMParser();
                    const svgDoc = parser.parseFromString(svgContent, 'image/svg+xml');
                    const svgElement = svgDoc.documentElement;
                    
                    // 创建渐变ID
                    const gradientId = 'gradient-' + Date.now();
                    
                    // 创建渐变定义
                    let gradient = '';
                    if (direction === 'horizontal') {
                        gradient = `<linearGradient id="${gradientId}" x1="0%" y1="0%" x2="100%" y2="0%">
                            <stop offset="0%" stop-color="${startColor}" />
                            <stop offset="100%" stop-color="${endColor}" />
                        </linearGradient>`;
                    } else if (direction === 'vertical') {
                        gradient = `<linearGradient id="${gradientId}" x1="0%" y1="0%" x2="0%" y2="100%">
                            <stop offset="0%" stop-color="${startColor}" />
                            <stop offset="100%" stop-color="${endColor}" />
                        </linearGradient>`;
                    } else if (direction === 'diagonal') {
                        gradient = `<linearGradient id="${gradientId}" x1="0%" y1="0%" x2="100%" y2="100%">
                            <stop offset="0%" stop-color="${startColor}" />
                            <stop offset="100%" stop-color="${endColor}" />
                        </linearGradient>`;
                    } else if (direction === 'radial') {
                        gradient = `<radialGradient id="${gradientId}" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
                            <stop offset="0%" stop-color="${startColor}" />
                            <stop offset="100%" stop-color="${endColor}" />
                        </radialGradient>`;
                    }
                    
                    // 添加渐变定义到SVG
                    const defs = svgDoc.createElement('defs');
                    defs.innerHTML = gradient;
                    svgElement.insertBefore(defs, svgElement.firstChild);
                    
                    // 应用渐变填充
                    const elementsToColor = svgElement.querySelectorAll('path, circle, rect, ellipse, polygon, line, polyline');
                    elementsToColor.forEach(element => {
                        if (element.hasAttribute('fill') && element.getAttribute('fill') !== 'none') {
                            element.setAttribute('fill', `url(#${gradientId})`);
                        }
                    });
                    
                    const processedSvg = new XMLSerializer().serializeToString(svgDoc);
                    resolve(processedSvg);
                });
            }

            function processImageGradient(imageDataUrl, startColor, endColor, direction) {
                return new Promise((resolve) => {
                    const img = new Image();
                    img.onload = function() {
                        const canvas = document.createElement('canvas');
                        canvas.width = img.width;
                        canvas.height = img.height;
                        
                        const ctx = canvas.getContext('2d');
                        
                        // 绘制原始图像作为蒙版
                        ctx.drawImage(img, 0, 0);
                        
                        // 创建渐变
                        let gradient;
                        if (direction === 'horizontal') {
                            gradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
                        } else if (direction === 'vertical') {
                            gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
                        } else if (direction === 'diagonal') {
                            gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
                        } else if (direction === 'radial') {
                            gradient = ctx.createRadialGradient(
                                canvas.width / 2, canvas.height / 2, 0,
                                canvas.width / 2, canvas.height / 2, Math.max(canvas.width, canvas.height) / 2
                            );
                        }
                        
                        gradient.addColorStop(0, startColor);
                        gradient.addColorStop(1, endColor);
                        
                        // 应用渐变
                        ctx.globalCompositeOperation = 'source-in';
                        ctx.fillStyle = gradient;
                        ctx.fillRect(0, 0, canvas.width, canvas.height);
                        
                        resolve(canvas.toDataURL('image/png'));
                    };
                    img.src = imageDataUrl;
                });
            }

            function processImageColor(imageDataUrl, color) {
                return new Promise((resolve) => {
                    const img = new Image();
                    img.onload = function() {
                        const canvas = document.createElement('canvas');
                        canvas.width = img.width;
                        canvas.height = img.height;
                        
                        const ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0);
                        
                        // 应用颜色滤镜
                        ctx.globalCompositeOperation = 'source-in';
                        ctx.fillStyle = color;
                        ctx.fillRect(0, 0, canvas.width, canvas.height);
                        
                        resolve(canvas.toDataURL('image/png'));
                    };
                    img.src = imageDataUrl;
                });
            }

            function convertSvgToPng(svgContent) {
                return new Promise((resolve) => {
                    const svgBlob = new Blob([svgContent], {type: 'image/svg+xml'});
                    const svgUrl = URL.createObjectURL(svgBlob);
                    
                    const img = new Image();
                    img.onload = function() {
                        const canvas = document.createElement('canvas');
                        canvas.width = img.width;
                        canvas.height = img.height;
                        
                        const ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0);
                        
                        canvas.toBlob(resolve, 'image/png');
                        URL.revokeObjectURL(svgUrl);
                    };
                    img.src = svgUrl;
                });
            }

            function downloadFile(content, filename, mimeType) {
                const blob = new Blob([content], {type: mimeType});
                downloadBlob(blob, filename, mimeType);
            }

            function downloadBlob(blob, filename, mimeType) {
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = filename;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
            }

            function updateStatus(message) {
                statusBar.textContent = message;
                setTimeout(() => {
                    statusBar.textContent = '';
                }, 3000);
            }
        });
    </script>
</body>
</html>